﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WWNotice.Utils
{
    public class HttpUtil
    {
        public static string PostFormDataRequest(Dictionary<string, object> formData, string requestUrl, int time = 10000)
        {
            return PostFormDataRequest(formData, requestUrl, new Dictionary<string, string>(), time);
        }
        public static string PostJsonRequest(string requestJson, string requestUrl, int time = 10000)
        {
            return PostJsonRequest(requestJson, requestUrl, new Dictionary<string, string>(), time);
        }

        public static string PostJsonRequest(string requestJson, string requestUrl, Dictionary<string, string> headers, int time = 10000)
        {
            var result = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            //发送post请求,相应的请求参数
            byte[] data = Encoding.GetEncoding("utf-8").GetBytes(requestJson);

            request.ContentType = "application/json; charset=utf8";


            return PostResponse(request, data, headers, time);
        }

        public static string PostFormDataRequest(Dictionary<string, object> formData, string requestUrl, Dictionary<string, string> headers, int time = 10000)
        {
            var result = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            //发送post请求,相应的请求参数
            StringBuilder dataStr = new StringBuilder();
            foreach (KeyValuePair<string, object> kv in formData)
            {
                if (kv.Value != null && kv.Key != null)
                {
                    dataStr.Append("&" + kv.Key + "=" + kv.Value);
                }

            }
            byte[] data = Encoding.GetEncoding("utf-8").GetBytes(dataStr.ToString().Trim('&'));
            
            request.ContentType = "application/x-www-form-urlencoded";
            

            return PostResponse(request, data,headers,time);
        }

        public static string PostResponse(HttpWebRequest request, byte[] data, Dictionary<string, string> headers, int time = 10000)
        {
            string result = string.Empty;
            request.Method = "Post";
            request.Accept = "application/json";
            request.ContentLength = data.Length;
            request.Timeout = time;
            foreach (KeyValuePair<string, string> kv in headers)
            {
                request.Headers.Add(kv.Key, kv.Value);
            }
            //响应流
            Stream responseStream;
            try
            {
                //请求流
                Stream requetStream = request.GetRequestStream();
                requetStream.Write(data, 0, data.Length);
                requetStream.Close();


                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();
            }
            catch (Exception e)
            {
                Environment.Exit(0);
                return "请求服务器异常";
            }

            if (responseStream != null)
            {
                StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                //获取返回信息
                result = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
            }



            return result;
        }


        /// <summary> Get方法获取某URL的页面内容</summary>
        /// <param name="url">网址</param>
        /// <param name="encoding">编码</param>
        /// <returns>页面内容</returns>
        public static string GetResponse(string url, string encoding = "UTF-8", int timeOut = 10000)
        {
            string result = string.Empty;
            try
            {
                ////处理HttpWebRequest访问https有安全证书的问题（ 请求被中止: 未能创建 SSL/TLS 安全通道。）
                //ServicePointManager.Expect100Continue = true;
                //ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                //request.UserAgent = "Opera/9.25 (Windows NT 6.0; U; en)";
                request.Timeout = timeOut;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream resStream = response.GetResponseStream();
                Encoding encode = Encoding.GetEncoding(encoding);
                if (resStream != null)
                {
                    StreamReader readStream = new StreamReader(resStream, encode);
                    Char[] read = new Char[256];
                    int count = readStream.Read(read, 0, 256);
                    while (count > 0)
                    {
                        String str = new String(read, 0, count);
                        result = result + str;
                        count = readStream.Read(read, 0, 256);
                    }
                    resStream.Close();
                    readStream.Close();
                }
                response.Close();
                request.Abort();
            }
            catch(Exception e)
            {
                return string.Empty;
            }
            return result;
        }
    }
}
